# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.views.generic import TemplateView
from django.contrib.auth.hashers import check_password, make_password
from django.contrib import auth

from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from rest_framework.parsers import JSONParser, FormParser
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView

import base64

from member.models import Member
from member.serializers import LoginSerializer, RegisterSerializer

# Create your views here.


class MenuView(TemplateView):
    
    template_name = 'member/menu.html'


class Login(APIView):

    parser_classes = (JSONParser, FormParser)
    permission_classes = (AllowAny,)
    authentication_classes = ()

    def post(self, request, *args, **kwargs):
        username = request.data.get('username', None)
        password = request.data.get('password', None)
        password = base64.b64decode(password)
        try:
            member = Member.objects.get(username=username)
            if check_password(password, member.password):
                auth.login(request, member)
                ret = {
                    'code': 200,
                    'msg': '登陆成功'
                }
                return Response(ret)
            else:
                ret = {
                    'code': 401,
                    'msg': '密码错误'
                }
                return Response(ret)
        except Member.DoseNotExist:
            ret = {
                'code': 404,
                'msg': '用户名不存在'
            }
            return Response(ret)


class Register(APIView):

    permission_classes = (AllowAny,)
    authentication_classes = ()
    parser_classes = (JSONParser, FormParser)

    def post(self, request, *args, **kwargs):
        r_serializer = RegisterSerializer(data=request.data)
        if r_serializer.is_valid():
            raw_password = r_serializer.validated_data['password']
            raw_password = base64.b64decode(raw_password)
            r_serializer.validated_data['password'] = make_password(raw_password)
            r_serializer.save()
            ret = {
                'code': 200,
                'msg': '注册成功'
            }
            return Response(ret)
        else:
            ret = {
                'code': 400,
                'msg': '参数错误',
                'errors': r_serializer.errors()
            }
            return Response(ret)
